package cn.sylinx.horm.core.datasource.dynamic;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;

import cn.sylinx.horm.util.ClassUtil;

class SPIManager {

    private static DynamicDatasourceProvider dynamicDatasourceProvider;

    private static final ReentrantLock lock = new ReentrantLock();

    static DynamicDatasourceProvider getDynamicDatasourceProvider() {

        if (dynamicDatasourceProvider != null) {
            return dynamicDatasourceProvider;
        }

        // 加載DynamicDatasourceProvider
        loadDynamicDatasourceProvider();

        return dynamicDatasourceProvider;

    }

    private static void loadDynamicDatasourceProvider() {

        try {

            lock.lock();

            if (dynamicDatasourceProvider == null) {

                ServiceLoader<DynamicDatasourceProvider> sl = ServiceLoader.load(DynamicDatasourceProvider.class,
                        ClassUtil.getDefaultClassLoader());
                Iterator<DynamicDatasourceProvider> it = sl.iterator();
                dynamicDatasourceProvider = it.hasNext() ? it.next() : null;
            }

            if (dynamicDatasourceProvider == null) {
                dynamicDatasourceProvider = new DefaultDynamicDatasourceProvider();
            }

        } finally {
            lock.unlock();
        }

    }

}
